/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.mailTemplate;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.parsers.html.HTMLPlainTextExtractor;
import com.blandware.atleap.common.util.ConvertUtil;
import com.blandware.atleap.model.core.MailTemplate;
import com.blandware.atleap.service.core.MailTemplateManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.MailTemplateForm;
import com.blandware.atleap.webapp.util.core.LocaleUtil;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * <p>Prepares form bean to update mail template body data
 * </p>
 * <p><a href="CallUpdateMailTemplateAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.14 $ $Date: 2008/04/29 17:48:08 $
 * @struts.action name="mailTemplateForm"
 * input="inputForward"
 * path="/core/mailTemplate/callUpdateBody"
 * scope="request"
 * validate="false"
 * roles="core-mailTemplate-update"
 * @struts.action-forward name="inputForward"
 * path=".core.mailTemplate.update"
 * @struts.action-forward name="updateMailTemplateBody"
 * path=".core.mailTemplate.updateBody"
 * @struts.action-forward name="listMailTemplates"
 * path="/core/mailTemplate/list.do"
 * redirect="true"
 */
public final class CallUpdateMailTemplateBodyAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		if ( isCancelled(request) ) {
            request.removeAttribute(WebappConstants.MAIL_TEMPLATE_MERGED_BODY_KEY);
            return mapping.findForward("listMailTemplates");
		}

		MailTemplateForm mailTemplateForm = (MailTemplateForm) form;
		Long mailTemplateId;
		if ( !GenericValidator.isBlankOrNull(mailTemplateForm.getId()) ) {
			mailTemplateId = Long.valueOf(mailTemplateForm.getId());
		} else if ( request.getSession().getAttribute(WebappConstants.MAIL_TEMPLATE_ID_KEY) != null ) {
			mailTemplateId = (Long) request.getSession().getAttribute(WebappConstants.MAIL_TEMPLATE_ID_KEY);
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing mail template ID. Returning to list...");
			}
			return mapping.findForward("listMailTemplates");
		}

		MailTemplateManager mailTemplateManager = (MailTemplateManager) getBean(Constants.MAIL_TEMPLATE_MANAGER_BEAN);
		MailTemplate mailTemplate = mailTemplateManager.retrieveMailTemplate(mailTemplateId);

		if ( mailTemplate == null ) {
			// mail template not found. it might be deleted by someone else
			ActionMessages errors = new ActionMessages();
			errors.add("mailTemplateNotFound", new ActionMessage("core.mailTemplate.errors.notFound"));
			saveErrors(request, errors);
			return mapping.findForward("listMailTemplates");
		}

		// check charset
		for ( Iterator i = mailTemplateForm.getCharsetMap().entrySet().iterator(); i.hasNext(); ) {
			Map.Entry entry = (Map.Entry) i.next();
			String localeIdentifier = (String) entry.getKey();
			String charset = (String) entry.getValue();
			if ( GenericValidator.isBlankOrNull(charset) ) {
				mailTemplateForm.setCharset(localeIdentifier, Constants.DEFAULT_ENCODING);
			} else if ( !WebappUtil.isCharsetSupported(charset) ) {
				ActionMessages errors = new ActionMessages();
				errors.add("notSupportedCharset", new ActionMessage("core.commons.errors.notSupportedCharset", charset));
				saveErrors(request, errors);
				saveToken(request);
				return mapping.getInputForward();
			}
		}

		// remove HTML markup, if this template was changed from html to plain text
		if ( !mailTemplate.isPlain() && Constants.MIME_TYPE_PLAIN.equalsIgnoreCase(mailTemplateForm.getMimeType()) ) {
			HTMLPlainTextExtractor extractor = new HTMLPlainTextExtractor();
			for ( Iterator i = mailTemplateForm.getBodyMap().entrySet().iterator(); i.hasNext(); ) {
				Map.Entry entry = (Map.Entry) i.next();
				String language = (String) entry.getKey();
				String body = (String) entry.getValue();
				InputStream bodyIS = new ByteArrayInputStream(ConvertUtil.convertToByteArray(body));
				StringWriter sw = new StringWriter();
				extractor.extract(bodyIS, sw, Constants.DEFAULT_ENCODING);
				mailTemplateForm.setBody(language, sw.toString().trim());
			}
		}
		// export available variables to session

		if ( mailTemplate.getAvailableVariables() != null && !mailTemplate.getAvailableVariables().isEmpty() ) {
			request.getSession().setAttribute(WebappConstants.MAIL_TEMPLATE_AVAIALABLE_VARIABLES_KEY, ConvertUtil.convertListToString(mailTemplate.getAvailableVariables(), ", "));
		} else {
			request.getSession().removeAttribute(WebappConstants.MAIL_TEMPLATE_AVAIALABLE_VARIABLES_KEY);
		}

		List contentLocales = LocaleUtil.getInstance(servlet.getServletContext()).getEnabledLocales();

		request.getSession().setAttribute(WebappConstants.CONTENT_LOCALES_COLLECTION_KEY, contentLocales);

		return mapping.findForward("updateMailTemplateBody");
	}

}